package com.example.demo.controller;


import com.aliyuncs.utils.StringUtils;
import com.example.demo.service.SendSms;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin  // 跨域支持
public class SmsApiController {

    @Autowired
    private SendSms sendSms;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("send/{phone}")
    public String code(@PathVariable("phone") String phone){
        // 调用发送方法，模拟真实业务
        String code = redisTemplate.opsForValue().get(phone);  // 首先去redis去寻找是否缓存这个手机号
        if(!StringUtils.isEmpty(code)){
            return phone + ":" + code + "已存在,未过期";
        }
        // 生成验证码并存储到redis中
        code = UUID.randomUUID().toString().substring(0,6);
        HashMap<String,Object> parm = new HashMap<>();
        parm.put("code",code);

        boolean isSend = sendSms.send(phone, "...", parm);

        if(isSend){
            redisTemplate.opsForValue().set(phone,code,10, TimeUnit.SECONDS);    // 设置过期时间10秒
            return phone + ":" + code + "发送成功";
        }else{
            return phone + ":" + code + "发送失败";
        }

    }


}
